package com.tsinghuabigdata.edu.ddmath.module.neteaseim.education.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.avchat.AVChatCallback;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.model.AVChatChannelInfo;
import com.tsinghuabigdata.edu.commons.codec.MD5Utils;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.activity.RoboForToolBarActivity;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.NeteaseLoginModel;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.NimCache;
import com.tsinghuabigdata.edu.ddmath.module.neteaseim.education.module.ChatRoomHttpClient;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.AppUtils;
import com.tsinghuabigdata.edu.ddmath.view.MyProgressDialog;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by hzxuwen on 2016/4/19.
 */
public class EnterRoomActivity extends RoboForToolBarActivity implements View.OnClickListener {
    private static final String EXTRA_DATA = "EXTRA_DATA";
    private static final int PERMISSION_REQUEST_CODE = 10;
    private static final String TAG = EnterRoomActivity.class.getSimpleName();

    @ViewInject(R.id.et_room)
    EditText etRoom;
    @ViewInject(R.id.bt_enterroom)
    Button btEnterroom;
    @ViewInject(R.id.bt_createroom)
    Button btCreatroom;
    @ViewInject(R.id.et_loginname)
    TextView etLoginname;
    @ViewInject(R.id.et_passwd)
    private TextView etPasswd;
    @ViewInject(R.id.bt_loginnim)
    Button btLoginim;

    private Context context;

    private boolean isCreate = false; // 主持人创建房间 true，其他成员进入房间 false
    private MyProgressDialog progressDialog;
    private NeteaseLoginModel nimLoginModel;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_enter_room;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        x.view().inject(this);

        isCreate = getIntent().getBooleanExtra(EXTRA_DATA, false);

        btEnterroom.setOnClickListener(this);
        btCreatroom.setOnClickListener(this);
        btLoginim.setOnClickListener(this);

        registerObservers(true);

        progressDialog = new MyProgressDialog(context);
        nimLoginModel = new NeteaseLoginModel();

//        etLoginname.setText("doudou");
//        etPasswd.setText("123456");
        etLoginname.setText("15014038032");
        etPasswd.setText("123456");
        etRoom.setText("test123456");

//        enterRoom();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        registerObservers(false);
    }

    private void registerObservers(boolean register) {
        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(userStatusObserver, register);
    }

    Observer<StatusCode> userStatusObserver = new Observer<StatusCode>() {
        @Override
        public void onEvent(StatusCode statusCode) {
            if (statusCode.wontAutoLogin()) {
                AlertManager.toast(context, "被踢出");
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_createroom:
                isCreate = true;
                break;
            case R.id.bt_enterroom:
                isCreate = false;
                break;
            case R.id.bt_loginnim:
                loginim();
                return;
        }
        if (AppUtils.isNoNetwork()) {
            Toast.makeText(EnterRoomActivity.this, "no network", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(etRoom.getText().toString().trim())) {
            Toast.makeText(this, "不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (checkPermission()) {
            createOrEnterRoom();
        } else {
            requestPermissions();
        }

    }

    private void loginim() {
        progressDialog.setMessage("登录中");
        progressDialog.show();
        final String account = etLoginname.getText().toString().trim();
        String passwd = etPasswd.getText().toString().trim();
        final String token = MD5Utils.stringToMD5(passwd);
        nimLoginModel.loginNim(account, token, new NeteaseLoginModel.NeteaseListener() {
            @Override
            public void onSuccess(Object res) {
                progressDialog.dismiss();
                LoginInfo loginfo = (LoginInfo) res;
                AlertManager.toast(context, "登录成功");
            }

            @Override
            public void onFailed(int code) {
                progressDialog.dismiss();
                AlertManager.toast(context, "登录失败 code " + code);

            }

            @Override
            public void onException(Throwable ex) {
                progressDialog.dismiss();
                AlertManager.toast(context, "登录异常");
            }
        });
    }

    // 创建房间
    private void createRoom() {
        progressDialog.setMessage("创建房间");
        progressDialog.show();
        //可以用自己的
        ChatRoomHttpClient.getInstance().createRoom(NimCache.getAccount(), etRoom.getText().toString(), new ChatRoomHttpClient.ChatRoomHttpCallback<String>() {
            @Override
            public void onSuccess(String s) {
                progressDialog.dismiss();
                createChannel(s);
            }

            @Override
            public void onFailed(int code, String errorMsg) {
                progressDialog.dismiss();
//                DialogMaker.dismissProgressDialog();
                Toast.makeText(EnterRoomActivity.this, "创建房间失败, code:" + code + ", errorMsg:" + errorMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 创建会议频道
     */
    private void createChannel(final String roomId) {
        progressDialog.setMessage("create channel");
        progressDialog.show();
        AVChatManager.getInstance().createRoom(roomId, "avchat test", new AVChatCallback<AVChatChannelInfo>() {
            @Override
            public void onSuccess(AVChatChannelInfo avChatChannelInfo) {
//                DialogMaker.dismissProgressDialog();
                progressDialog.dismiss();
                AlertManager.toast(context, "创建会议频道成功");
//                ChatRoomActivity.start(EnterRoomActivity.this, roomId, true);
                finish();
            }

            @Override
            public void onFailed(int i) {
                progressDialog.dismiss();
//                DialogMaker.dismissProgressDialog();
                Toast.makeText(EnterRoomActivity.this, "创建频道失败, code:" + i, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onException(Throwable throwable) {
                progressDialog.dismiss();
//                DialogMaker.dismissProgressDialog();
            }
        });
    }

    // 进入房间
    private void enterRoom() {
//        ChatRoomActivity.start(EnterRoomActivity.this, roomEdit.getText().toString(), false);
        String roomid = etRoom.getText().toString().trim();
        Bundle bundle = new Bundle();
        bundle.putString(ChatRoomActivity.EXTRA_ROOM_ID, roomid);
        goActivity(ChatRoomActivity.class, bundle);
        finish();
    }

    private void requestPermissions() {
        final List<String> missed = AVChatManager.checkPermission(this);
        List<String> showRationale = new ArrayList<>();
        for (String permission : missed) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                showRationale.add(permission);
            }
        }

        if (showRationale.size() > 0) {
            new AlertDialog.Builder(this)
                    .setMessage("You need to allow some permission")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(EnterRoomActivity.this, missed.toArray(new String[missed.size()]),
                                    PERMISSION_REQUEST_CODE);
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .create()
                    .show();
        } else {
            ActivityCompat.requestPermissions(this, missed.toArray(new String[missed.size()]), PERMISSION_REQUEST_CODE);
        }
    }

    //检查所有的权限
    private boolean checkPermission() {
        final List<String> missed = AVChatManager.checkPermission(this);
        if (missed.size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (AVChatManager.checkPermission(this).size() == 0) {
                    createOrEnterRoom();
                } else {
                    Toast.makeText(EnterRoomActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

    private void createOrEnterRoom() {
//        DialogMaker.showProgressDialog(this, "", false);
        if (isCreate) {
            createRoom();
        } else {
            enterRoom();
        }
    }
}
